package com.king.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        String message = new String(msg.getContent(), CharsetUtil.UTF_8);

        System.out.println("服务器接收到的数据：" + message);
        System.out.println("服务器接收到的消息量 = " + (++this.count));

        // 服务器回送数据
        String str = UUID.randomUUID().toString();
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        ctx.writeAndFlush(new MessageProtocol(bytes.length, bytes));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
